package com.summer.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.reggie.common.CustomException;
import com.summer.reggie.dto.SetmealDto;
import com.summer.reggie.entity.Dish;
import com.summer.reggie.entity.Setmeal;
import com.summer.reggie.entity.SetmealDish;
import com.summer.reggie.mapper.SetmealMapper;
import com.summer.reggie.service.DishService;
import com.summer.reggie.service.SetmealDishService;
import com.summer.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者:夏天
 * qq:1205232048
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐, 同时需要保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息, 操作setmeal
        this.save(setmealDto);
        //保存套餐和菜品的关联信息, 操作setmealDish
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐以及和菜品的关联数据
     * @param ids 套餐id集合
     */
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态, 确定是否可用删除
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(setmealLambdaQueryWrapper);
        //如果不能删除, 抛出一个业务异常
        if(count > 0){
            throw new CustomException("该套餐还在售卖, 无法删除");
        }
        //如果可以删除, 先删除Setmeal表中的数据
        this.removeByIds(ids);
        //再根据套餐id删除SetmealDish表中的数据
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
